<template>
  <div>
    <header-search v-show="isShow" :city="getCity" :isFixed="isFixed" ref="searchDom">
    </header-search>
    <template v-if="isShow">
      <div class="padding_lr whiteBg">
        <!-- 轮播图 -->
        <slide-img :divStyle="1" :bannerArry='banner'></slide-img>
      </div>
      <!--nav 主分类-->
      <nav class="white_bg">
        <ul class="navUl">
          <li v-for="(item,index) in findMenu">
            <a @click="navList(item.dictValue,item.dictId)" v-for="(item2,index2) in imgs" v-if="index==index2">
              <img :src="item2.imgUrl" alt="">
            </a>
            <p>{{item.dictValue}}</p>
          </li>
        </ul>
      </nav>
      <!--没有热门商圈的时候加个间距-->
      <div class="div_space" v-if="!homeGoodCoupon.length"></div>
      <!--end-->

      <!--热门商圈-->
      <homeGoodCouponCarousel :num='num' :homeGoodCouponParameter='homeGoodCouponParameter' :homeGoodCoupon='homeGoodCoupon'></homeGoodCouponCarousel>
      <!--热门商圈end-->
      <newMchtBanner></newMchtBanner>
      <position :info="info" v-if="mchtListInfo.length"></position>
      <template v-for="(item,index) in mchtListInfo">
        <mchtListInfo :mchtInfo="item">
          <div class="div_space" v-if="(index+1) != mchtListInfo.length"></div>
        </mchtListInfo>
      </template>

    </template>
    <no-data v-if="!mchtListInfo.length"></no-data>
    <modal @close_modal="close_modal($event)" v-show="couponShow">
      <div class="couponR" v-show="couponRewardShow">
        <div>恭喜你! 获得一笔扫码奖励金</div>
        <div>如被人使用更有机会获得神秘大奖哟</div>
        <div class="cont">
          <img src="../../images/useReward.png" alt="">
          <div class="detail">
            <div class="total"><span>¥ </span>{{usrAmt}}<span>元</span></div>
            <div class="all">总计</div>
          </div>
        </div>
        <div>扫码奖励金已经放入您的钱包</div>
      </div>
      <div class="couponB" v-show="couponDetailShow">
        <img src="../../images/couponLight.png" alt="">
        <div class="content">
          <img class="couponBKG imgs" src="../../images/couponBKG.png" alt="">
          <card :couponContent="couponContent"
                style="position:absolute;bottom:-7%;height:42%;width:75%;margin-left:12.5%;background:rgba(255,255,255,.2);z-index:5; border-radius: 2px;"/>
          <img style="z-index:6;" class="couponPre imgs" src="../../images/couponPre.png" alt="">
          <img class="yellowstar star " src="../../images/yellowstar.gif" alt="">
          <img class="whitestar1 star " src="../../images/whitestar.gif" alt="">
          <img class="whitestar2 star " src="../../images/whitestar.gif" alt="">
          <span @click="goCardList">去商券查看 &gt;</span>
        </div>
      </div>
    </modal>
    <!--<div class="activities game_icon" @click="activities('game')"></div>-->
    <div class="activities ballot_icon" @click="activities('ballot')" v-if="ballotState"></div>
    <games v-if="NewUsrBag" @close="NewUsrBag = false"></games>
    <!--num值是1时为"首页"引导页-->
    <landing-page v-if="!NewUsrBag" :num="landingPageNum"></landing-page>
    <footer-view></footer-view>
  </div>
</template>
<script>
  import HeaderSearch from "./header_search.vue";
  import * as types from "../../vuex/types.js";
  import getData from "../../service/getData.js";
  import getData2 from "../../service/getData2.js";
  import getData4 from "../../service/getData4.js";
  import store from 'src/vuex/index.js'

  import listLoading from "../../componentes/global/listLoading.vue";

  import {newUser, ballotStatue} from "../../service/getData3.js";
  import Games from "src/pages/activities/games/index.vue";
  import {mapState} from "vuex";
  import {Toast, Indicator, MessageBox} from "mint-ui";
  import landingPage from "../../componentes/global/landingPage.vue";
  import {Common} from "src/utils/common.js";
  import {Storage} from "src/utils/storage.js";
  import Card from "./card";
  import newMchtBanner from './newMchtBanner.vue'

  export default {
    name: "main",
    components: {
      Games,
      HeaderSearch,
      landingPage,
      listLoading,
      Card,
      newMchtBanner,
      homeGoodCouponCarousel: () => import('src/componentes/local/homeGoodCouponCarousel.vue'),
      mchtListInfo: () => import('src/componentes/local/home-mchtList'),
      position: () => import('src/componentes/local/position.vue')

    },
    data() {
      return {
        city: "", // 存城市
        findMenu: [],
        banner: [],
        couponList: [],
        showCity: true,
        couponShow: false,
        couponRewardShow: false,
        couponDetailShow: false,
        usrAmt: 0,
        couponContent: {},
        info: {title: "附近好店", cue: "和你一起，发现身边的小美好", bColor: true},
        mchtListInfo: [],
        imgs: [
          {imgUrl: require('./images/meishi.png')},
          {imgUrl: require('./images/life.png')},
          {imgUrl: require('./images/yule.png')},
          {imgUrl: require('./images/shopping.png')},
          {imgUrl: require('./images/beauty.png')},
          {imgUrl: require('./images/healthcare.png')},
          {imgUrl: require('./images/parenting.png')},
          {imgUrl: require('./images/eShop.png')}
        ],
        couponType: [
          {
            key: "all",
            isChecked: true,
            value: "全部"
          },
          {
            key: "cash",
            isChecked: false,
            value: "代金券"
          },
          {
            key: "rebate",
            isChecked: false,
            value: "折扣券"
          },
          {
            key: "voucher",
            isChecked: false,
            value: "抵用券"
          }
        ],
        checkedType: "all",
        isShow: true,
        NewUsrBag: false,
        isFixed: false,
        backHome: false,
        landingPageNum: 0, //1: "首页"引导页，0: 闭值
        ballotState: false, // 投票状态
        currentPage: 0,
        loading: true,
        noMoreCoupon: true,
        moreInfo: false,
        upperDictId: "", //子类型id
        cityState: false,
        isGO: false,
        homeGoodCoupon: [],//商券好券（首页手触轮播）
        homeGoodCouponParameter: {},
        num: '1'
      };
    },
    watch: {
      city(newVal, old) {
        // 监听城市切换
        this.getMchtListInfo()
        this.marketGoodCouponPosHome()

      },
      couponShow(value) {
        window.isScroll = value;
      },
      landingPageNum(value) {
        window.isScroll = !!value
      },
      NewUsrBag(value) {
        window.isScroll = value
      },
    },
    created: async function () {
      Storage.remove("hasPayOrder")//清除订单信息
      Storage.remove("cardListState", true); //公众号进入我的券包，只有分享和使用按钮
      let city = Storage.get("city", true);
      // alert(this.city)
      let sit_position = Storage.get("sit", true);
      // console.log( sit_position)
      if (!city && !sit_position) {
        Indicator.open("正在获取距离...");
        setTimeout(() => { // 6秒后关闭loading
          if (Indicator.open.length > 0) {
            Indicator.close();
            this.city = Storage.get("city", true) || "上海";
            Storage.set("city", this.city, true);
          }
        }, 6000)
        let that = this;
        wx.ready(res => {
          wx.getLocation({
            type: "gcj02",
            success: async res => {
              let sit = res.longitude + "," + res.latitude;
              that.getCoupon(sit);
              that.$store.commit("usr_position", sit);
              let data = await getData.getSite(sit);
              if (data.respCode === "00") {
                if (data.content.city.trim()) {
                  that.city = data.content.city;
                } else {
                  that.city = data.content.province;
                }
                that.cityState = true;
                Storage.set("city", that.city, true);
              } else {
                Toast({
                  message: rep.errorInfo,
                  duration: 2000
                });
              }
              Indicator.close();
            },
            fail() {
              // 接口调用完成时执行的回调函数，无论成功或失败都会执行
              that.getCoupon();
              that.city = "上海";
              Storage.set("city", "上海", true);
              Indicator.close();
            },
            async complete() {
              // 接口调用完成时执行的回调函数，无论成功或失败都会执行
              if (!city) {
                that.city = "上海";
                Storage.set("city", that.city, true);
              }
              Indicator.close();
              if (!that.NewUsrBag) {
                await that.isNewUsr();
              }
            },
            cancel: function () {
              // 这个地方是用户拒绝获取地理位置
              if (!city) {
                that.city = "上海";
                Storage.set("city", that.city, true);
              }
              Indicator.close();
              // that.isNewUsr();
            }
          });
        });
      } else {
        this.getCoupon(sit_position);
      }
      if (city) {
        this.city = city;
      }
      this.findHead();
      this.homeBanner();

      window.addEventListener("scroll", this.handleScroll);
      // 判断投票活动是否开启
      ballotStatue().then(res => {
        if (res.respCode === "00") {
          let data = res.content;
          this.ballotState = data.id !== 0; // 0 未开启 非0 开启
        } else {
          Toast({
            message: rep.errorInfo,
            duration: 1000
          });
        }
      });

      //解决ios返回出现空白问题
      setTimeout(function () {
        window.scrollTo(0, 1);
        window.scrollTo(0, 0);
      }, 100);

    },
    computed: {
      ...mapState({
        userInfo: state => state.user.userInfo,
        openId: state => state.user.openId,
        sit: state => state.coupon.position
      }),
      getCity() {
        return this.city || Storage.get('city', true)
      }
    },
    mounted: function () {
      this.$nextTick(() => {
        document.body.scrollTop = 0;
        this.$store.commit("history_info", Storage.get("history_info")); //设置搜索历史
      });
    },
    methods: {
      async getMchtListInfo() {
        let rep = await getData4.getHomeMchtListInfo({
          data: {
            cityName: Storage.get('city', true),
            position: Storage.get('sit', true)
          }
        })
        if (rep.content) {
          if (Object.keys(rep.content).length) {
            this.mchtListInfo = rep.content.mchtList;
          } else {
            this.mchtListInfo = []
          }
        }


      },
      // 通过消息获得优惠券
      async getCoupon(sit) {
        let searchParams = this.$route.query;
        let data = {};
        try {
          if (searchParams.baid && searchParams.type && searchParams.time && searchParams.usrId) {
            if (!sit) {
              await MessageBox("开启定位才能获取优惠券哦！");
              return;
            }
            let usrId = Storage.get("usrId", false);
            if (searchParams.usrId != usrId) {
              await MessageBox("这个电子券不属于您哦！");
              return;
            }
            let options = {};
            data.baId = searchParams.baid;
            data.time = searchParams.time;
            data.signLongitude = Number(sit.split(",")[0]).toFixed(8);
            data.signLatitude = Number(sit.split(",")[1]).toFixed(8);
            data.usrId = usrId;
            options.method = "POST";
            options.data = data;
            getData2
              .getCouponFromInfo(options)
              .then(data => {
                let con = data.content;
                if (!con) {
                  MessageBox(data.errorInfo);
                  return;
                }
                let time = con.coupon.validatyEnd;
                this.couponContent = {
                  mchtName: con.mchtName,
                  comScore: con.coupon.comScore,
                  denomination: con.coupon.denomination,
                  type: con.coupon.type,
                  validatyEnd:
                  time.slice(0, 4) +
                  "-" +
                  time.slice(4, 6) +
                  "-" +
                  time.slice(6),
                  name: con.coupon.name,
                  comNum: con.coupon.comNum
                };
                this.couponShow = true;
                if (con.usrAmt > 0) {
                  this.usrAmt = con.usrAmt
                  this.couponRewardShow = true
                  setTimeout(() => {
                    this.couponRewardShow = false
                    this.couponDetailShow = true
                  }, 3000);
                } else {
                  this.couponDetailShow = true
                }
              })
              .catch(function (err) {
              })
              .finally(() => {
              });
          }
        } catch (error) {
        }
      },
      goCardList() {
        this.$router.push({
          name: 'cardList'
        })
        this.couponShow = false
        this.couponRewardShow = false
        this.couponDetailShow = false
      },
      close_modal($event) {
        if (!this.couponDetailShow) {
          $event.preventDefault()
          return
        }
        setTimeout(() => {
          this.isGo = true
        }, 800)
        if (this.isGo) {
          this.couponShow = false
          this.isGo = false
        }
      },
      async isNewUsr() {
        // 判断是否为新用户
        let data = await newUser({
          usrId: this.userInfo.usrId
        });
        if (data.respCode == "00") {
          // if (this.sit) {
          this.NewUsrBag = true;
          // }
          this.landingPageNum = 1;
          Storage.set("firstEntry", true, true);
        } else if (data.respCode != "00") {
          this.NewUsrBag = false;
          this.landingPageNum = 0;
        }
      },
      handleScroll() {
        //监听滚动事件
        let scrollTop =
          document.documentElement.scrollTop || document.body.scrollTop;
        this.isFixed = scrollTop >= 27.3 * 2;
      },
      activities(type) {
        if (type === "game") {
          this.$router.push({
            name: "game",
            params: {
              id: 1
            } // 铲子id 1
          });
        } else if (type === "ballot") {
          ballotStatue().then(res => {
            if (res.respCode === "00") {
              let data = res.content;
              if (data.ifClose) {
                Toast({
                  message: "活动暂时关闭！",
                  duration: 1000
                });
              } else if (data.ifEnd) {
                this.$router.push({
                  name: "ballot-result",
                  query: {
                    id: data.id
                  }
                });
              } else {
                this.$router.push({
                  name: "ballot",
                  query: {
                    id: data.id
                  }
                });
              }
            } else {
              Toast({
                message: rep.errorInfo,
                duration: 1000
              });
            }
          });
        }
      },
      // closeGift() {
      //   this.NewUsrBag = false
      // },
//    changeCity(city) {
//      this.city = city;
//      this.currentPage = 0;
//      this.couponList = [];
//      Storage.set("city", this.city, true);
//      this.homeGoodCoupon = []//每次清空，防止数据增多
//      // 猜你喜欢
//      if (this.city == "全部") {
//        this.moreList1();
////          this.marketGoodCouponPosHome()
//      } else {
//        this.moreList();
////        this.marketGoodCouponPosHome()
//      }
//      this.homeGoodCoupon = []//每次清空，防止数据增多
//    },
      search(value) {
        this.$router.push({
          name: "couponSearch"
        });
      },
      hideMainView(value) {
        this.isShow = value;
        this.showCity = value;
      },
      // 选择电子券类型
      choCouType(index, type) {
        this.currentPage = 0;
        this.couponList = [];
        this.couponType.forEach(item => {
          item.isChecked = false;
        });
        this.couponType[index].isChecked = true;
        this.checkedType = type;
        this.moreList(); // 请求
      },
      moreList() {
      },
      navList: function (key, upperDictId) {
        this.$router.push({
          path: '/classifySearchMcht',
          query: {dictId: upperDictId}
        })
//        this.$store.commit('search_type', 'mecth', true) //保证每次进去都是商户
//        this.$store.commit("search_key", '');
//        let me = this;
//        me.$store.commit("coupon_tit", key);
//        me.$store.commit(types.GET_PAGE_NUM, 1); // 重置分页为1
//        getData2.upperDictId({}, upperDictId).then(function (rep) {
//          Storage.set("menuArr", rep.content, true);
//          Storage.set(
//            "menuArrMess",
//            {
//              menuArrId: upperDictId,
//              tit: key
//            },
//            true
//          );
//          me.$router.push({
//            name: "couponSearch"
//          });
//        });
      },
      //类型
      findHead: function () {
        var me = this;
        getData2.newFindType().then(function (rep) {
          rep.content.info.length = 8;
          me.findMenu = rep.content.info;
          Storage.set("menu", rep.content.info, true);
        });
      },
      //首页广告
      homeBanner: function () {
        var me = this;
        getData2.homeBanner({}).then(function (rep) {
          me.banner = rep.content.bannerList;
        });
      },
      //商券手触轮播有定位数据
      async marketGoodCouponPosHome() {
        await getData4.marketGoodCouponPosHome({
          data: {
            cityName: this.city,
            position: this.sit
          }
        }).then((res) => {
          if (res.respCode === "00") {
            this.homeGoodCoupon = []
            if (Object.keys(res.content).length) {
              this.homeGoodCouponParameter.tradingAreaAddr = res.content.tradingAreaAddr
              this.homeGoodCouponParameter.tradingAreaMchtName = res.content.tradingAreaMchtName
              if (res.content.mchtList.length > 6) {
                this.homeGoodCouponParameter.GreaterSix = true
                var data = res.content.mchtList
                this.homeGoodCoupon = res.content.mchtList
              } else {
                this.homeGoodCouponParameter.GreaterSix = false
                if (res.content.mchtList.length == 1) {
                  this.homeGoodCouponParameter.numOne = true
                } else {
                  this.homeGoodCouponParameter.numOne = false
                }
                this.homeGoodCoupon = res.content.mchtList
              }
            }
          } else {
            Toast({
              message: res.errorInfo,
              duration: 1000
            });
          }

        })
      },
    },
    activated() {
      this.$nextTick(() => {
        window.scrollTo(0, store.state.loading.homeScroll)// 首页还原位置
        this.num = 1//保证再次回来商圈数据为1
        this.city = Storage.get("city", true);
      });
    },
    beforeRouteLeave(to, from, next) {
      if (window.isBack) {
        window.isBack = false
        wx.closeWindow(); // 首页点击浏览器后退，关闭微信浏览器
        return
      }
      next();
      this.$store.commit("HOME_SCROLL", window.scrollY);
      setTimeout(() => window.scrollTo(0, 0), 400); // 还原位置
      Storage.remove("positiveScan", true); //保证清除正扫付款时候数据，避免第二次扫描进入有数值
    }
  };
</script>

<style scoped>
  .padding_lr {
    padding-top: 0.667rem;
  }

  .couponR {
    background: #ffffff;
    position: absolute;
    width: 75%;
    height: 55%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    margin: auto;
    border-radius: 0.5rem;
    transform: translateY(-20%);
    -webkit-transform: translateY(-20%);
  }

  .couponR img {
    display: block;
    max-width: 100%;
    margin-top: -2rem;
  }

  .couponR div {
    text-align: center;
  }

  .couponR div:nth-child(1):not(.total) {
    margin-top: 1.6rem;
    color: #ec4e8a;
    font-size: 1.3rem;
    font-weight: 400;
  }

  .couponR .cont {
    position: relative;
  }

  .couponR .detail {
    position: absolute;
    left: 0;
    right: 0;
    margin: auto;
    top: 7.3rem;
  }

  .couponR .detail div {
    margin-top: 0 !important;
  }

  .couponR .total {
    color: #ec4e8a;
    font-size: 1.3rem;
  }

  .couponR .total span {
    color: #9a1747;
    font-size: 0.6rem;
  }

  .couponR .all {
    font-size: 0.7rem;
    /* color: !important; */
  }

  .couponR div:nth-child(2) {
    margin-top: 0.2rem;
    color: #333;
    font-size: 0.9rem;
  }

  .couponR div:nth-last-child(1):not(.detail) {
    font-size: 0.7rem;
    margin-top: -1.6rem;
  }

  .couponB {
    position: relative;
  }

  .couponB img {
    max-width: 100%;
  }

  .couponB .content {
    position: absolute;
    width: 100%;
    height: 85%;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    text-align: center;
  }

  .couponB .content span {
    position: absolute;
    bottom: -5%;
    z-index: 10;
    transform: translateX(-50%);
    -webkit-transform: translateX(-50%);
    color: #eee;
    font-weight: 300;
    font-size: 0.9rem;
  }

  .couponB .star {
    max-width: 6%;
    position: absolute;
  }

  .couponB .yellowstar {
    bottom: -25%;
    left: 25%;
  }

  .couponB .whitestar1 {
    top: 45%;
    left: 15%;
    max-width: 3%;
  }

  .couponB .whitestar2 {
    top: 30%;
    right: 18%;
  }

  .couponB .imgs {
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    height: 115%;
  }

  .lastInfo {
    font-size: 1rem;
    text-align: center;
    color: #999;
  }

  nav {
    overflow: hidden;
    /*background: #fff;*/
    padding: 0 0.667rem;
  }

  .navUl {
    padding-bottom: 1.2rem;
    overflow: hidden;
  }

  nav li {
    float: left;
    width: 25%;
    text-align: center;
    color: #333;
  }

  nav li {
    margin-top: 1rem;
  }

  nav li p {
    font-size: .9rem;
    margin-top: 0.3rem;
    color: rgb(74, 74, 74);
  }

  nav img {
    width: 3.4em;
    height: 3.4em;
    vertical-align: -0.15em;
    fill: currentColor;
    overflow: hidden;
  }

  .activities {
    position: fixed;
    right: 1rem;
    width: 3.4rem;
    height: 3.4rem;
    background-size: 100%;
    z-index: 100;
  }

  .game_icon {
    background-image: url("../../images/game_icon.png");
    bottom: 5rem;
  }

  .ballot_icon {
    background-image: url("../../images/ballot_icon.png");
    bottom: 10rem;
  }

  /*商户列表描边*/
  /*.card_w_h{*/
  /*border-bottom: 1px solid #EDEDED;*/
  /*border-top: 1px solid #EDEDED;*/
  /*}*/

</style>
